﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Data;
using System.Data.SqlClient;

namespace Articles_Ajax
{
    /// <summary>
    /// LoadCommentsBySplitPage 的摘要说明
    /// </summary>
    public class LoadCommentsBySplitPage : IHttpHandler
    {

        #region ProcessRequest
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            //获取页面的动作
            String strAction = context.Request["action"].ToString();

            //获取当前页码
            String strPageNum = context.Request["page"].ToString();

            //获取当前延时加载的次数
            String strCount = context.Request["count"].ToString();


            String result = string.Empty;
            switch (strAction)
            {
                case "load":
                    result = LoadFirstPage();
                    break;
                case "pageOrlazy":
                    result = loadCommentsBySplitPage(strPageNum, strCount);
                    break;
                case "pagenumber":
                    result = loadPageNumber();
                    break;
                default:
                    break;
            }
            //将结果输出到客户端
            context.Response.Write(result);
        }
        #endregion

        #region 处理第一次加载页面
        /// <summary>
        /// 处理第一次加载页面
        /// </summary>
        /// <returns>经过序列化的用户昵称、评论的JSON字符串</returns>
        private String LoadFirstPage()
        {
            List<Comment> listComments = new List<Comment>();
            DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.ConnectionString, CommandType.Text, "select top(67) * from T_Comments where AID=200");
            if (ds != null)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Comment comment = new Comment()
                    {
                        UserNick = row["userName"].ToString(),
                        Message = row["msg"].ToString()
                    };
                    listComments.Add(comment);
                }
            }
            JavaScriptSerializer jss = new JavaScriptSerializer();
            //返回 经过序列化的 json格式字符串
            return jss.Serialize(listComments);
        }
        #endregion

        #region 处理延时或分页加载评论
        /// <summary>
        ///  处理延时或分页加载评论
        /// </summary>
        /// <param name="pageString">当前页面号</param>
        /// <param name="countString">延时加载评论的次数</param>
        /// <returns>分页之后的 ，经过序列化的用户昵称、评论的JSON字符串</returns>
        private String loadCommentsBySplitPage(String pageString, String countString)
        {
            Int32 pageTemp, countTemp;
            if (!Int32.TryParse(pageString, out pageTemp) || !Int32.TryParse(countString, out countTemp))
            {
                //throw new ArgumentException("页码参数或者评论加载次数的格式不正确!");
                return "参数传递-格式错误:" + pageString + "," + countString;
            }
            ///每页显示总评论30条
            ///每次延时加载一次评论，加载10条
            ///每页最多延时加载3次

            //计算需要加载评论的起始索引
            Int32 startIndex = (Int32.Parse(pageString) - 1) * 30 + Int32.Parse(countString) * 10 + 1;
            //计算需要加载评论的结束索引
            Int32 endIndex = startIndex + 9;
            SqlParameter[] parm = {
                                      new SqlParameter("@AID",200),
                                      new SqlParameter("@startIndex",startIndex),
                                      new  SqlParameter("@endIndex",endIndex)
                                  };
            List<Comment> listComments = new List<Comment>();
            DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.ConnectionString, "sp_SplitPage_T_Comments", parm);
            if (ds != null)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Comment comment = new Comment()
                    {
                        UserNick = row["userName"].ToString(),
                        Message = row["msg"].ToString()
                    };
                    listComments.Add(comment);
                }
            }
            JavaScriptSerializer jss = new JavaScriptSerializer();
            //返回 经过序列化的 json格式字符串
            return jss.Serialize(listComments);
        }
        #endregion

        #region 获取指定文章的总评论条数
        /// <summary>
        /// 获取指定文章的总评论条数
        /// </summary>
        /// <returns>评论总条数字符串</returns>
        private String loadPageNumber()
        {
            SqlParameter[] parm = { new SqlParameter("@AID", 200) };
            object objTotal = SqlHelper.ExecuteScalar(SqlHelper.ConnectionString, CommandType.Text, "select	COUNT(*)	from  dbo.T_Comments T where T.AID=@AID", parm);
            return (Int32.Parse(objTotal.ToString()) / 30).ToString();
        }
        #endregion

        #region IsReusable
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion

    }
}